package com.wavefront.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Hashtable;
import android.util.Log;
import com.wavefront.Model;
import com.wavefront.mtl.elements.Material;
import com.wavefront.obj.parser.LineParser;
import com.wavefront.obj.parser.MtlParser;

public class MtlLoader extends MtlParser {

	Hashtable<String, Material> materials = new Hashtable<String, Material>();

	public void load(String[] fileNames, Model contextModel) {

		for (int i = 1; i < fileNames.length; i++)
			load(fileNames[i], contextModel);

	}

	public void load(String fileName, Model contextModel) {
		Log.d("obj.mtl", "Loading mtl file :" + fileName);
		InputStream fileInput;
		String pathToMTL = MtlParser.getCurrentFolder() + fileName;
		try {

			File file = new File(pathToMTL);
			fileInput = new FileInputStream(file);

			BufferedReader in = new BufferedReader(new InputStreamReader(
					fileInput));

			String currentLine = null;
			while ((currentLine = in.readLine()) != null) {
				currentLine = currentLine.replaceAll("  ", " ");
				currentLine = currentLine.replaceAll("	", "");
				String[] lineWords = currentLine.split(" ");
				String lineType = lineWords[0];
				LineParser parser = MtlParser.getLineParser(lineType);
				parser.parse(lineWords);
			}

			if (in != null)
				in.close();

		} catch (Exception e) {
			e.printStackTrace();

			throw new RuntimeException("Error parsing :'" + pathToMTL + "'");
		}
	}

}